package com.example.wanxiang.controller;

import com.example.wanxiang.dto.ArticleDto;
import com.example.wanxiang.dto.ArticleReturn;
import com.example.wanxiang.entity.Article;
import com.example.wanxiang.entity.ArticleAndCom;
import com.example.wanxiang.service.ArticleAndComService;
import com.example.wanxiang.service.ArticleService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @Resource
    private ArticleAndComService articleAndComService;

    @GetMapping("/articleByTitleLike")
    public List<Article> articleList(@RequestParam String title) {
        return articleService.findByTitle(title);
    }

    @GetMapping("/articleByTitlePage")
    public ArticleReturn articleReturn(@RequestBody ArticleDto articleDto) {
        ArticleReturn articleReturn = new ArticleReturn();
        articleReturn.setArticleList(articleService.getArticleByTitle(articleDto));
        articleReturn.setCount(articleService.getArticleCount(articleDto));
        articleReturn.setPageNow(articleDto.getPage());
        articleReturn.setPageSize(articleDto.getSize());
        return articleReturn;
    }

    @GetMapping("/articlesFindAll")
    public List<Article> findAll() {
        return articleService.findAll();
    }

    @GetMapping("/articlesById/{id}")
    public Article findById(@PathVariable("id") String id) {
        return articleService.findById(id);
    }

    @PostMapping("/create")
    public Article create(@RequestBody ArticleDto articleDto) {
        Article article = new Article();
        article.setId(articleDto.getId());
        article.setAuthor(articleDto.getAuthor());
        article.setContent(articleDto.getContent());
        article.setAuthorCreatedTime(LocalDateTime.now());
        article.setType(articleDto.getType());
        article.setUserId(article.getUserId());
        article.setVisits(articleDto.getVisits());
        article.setState(articleDto.getState());
        article.setImageIds(articleDto.getImageIds());
        return articleService.save(article);
    }

    @PutMapping("/articleByUpdate/{id}")
    public Article update(@PathVariable("id") String id, Article article) {
        return articleService.update(id, article);
    }

    @DeleteMapping("/articleDelete/{id}")
    public void delete(@PathVariable("id") String id) {
        articleService.deleteById(id);
    }

    @GetMapping("/articles/{articleId}/andcoms")
    public List<ArticleAndCom> findArticleAndComById(@PathVariable String articleId) {
        return articleAndComService.findByArticleId(articleId);
    }


}
